package groovy;

import groovy.lang.*;
import org.codehaus.groovy.control.CompilerConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lingyun.wang on @date 2021/12/2
 */
public class GroovyRuleEngine {
    Logger log = LoggerFactory.getLogger(GroovyRuleEngine.class);
    private Script engineInstance;
    private Map<String,Script> mapping = new HashMap<String,Script>();
    public Script load(String scriptStr) throws Exception {
        CompilerConfiguration cc = new CompilerConfiguration();
        String classpath = "com.firesoon.engine.groovy.script"; // File.pathSeparator
        cc.setClasspath(classpath);
        // fileName 设置;
        // 如果不指定名称，则生成的Script名字都是一样的， 一个classloader只能加载同名的class一次，所以会生成大量的InnerLoader
        String scriptName = "Script123213";
        return new GroovyShell(cc).parse(scriptStr, scriptName);
    }

    public String register(String scriptId,String scriptStr){
        try {
            mapping.put(scriptId,load(scriptStr));
        } catch (Exception e) {
            log.warn("script groovy loadClass fail!scriptStr:{}",scriptStr);
            return null;
        }
        return scriptId;
    }
    public Object run(String scriptId,Map<String, Object> params){
        Script script = mapping.get(scriptId);
        script.setBinding(buildBind(params));
        return script.run();
    }

    private Binding buildBind(Map<String, Object> params) {
        Binding binding = new Binding();
        // bind parameters
        if (params != null) {
            for (Map.Entry<String, Object> entry : params.entrySet()) {
                String variableName = entry.getKey();
                Object value = entry.getValue();
                binding.setVariable(variableName, value);
            }
        }

        return binding;
    }
}
